﻿using System;
using System.Collections.Generic;
using System.Text;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MvvmDatabase.Models;
using MvvmDatabase.Services;
using MvvmHelpers;

namespace MvvmDatabase.ViewModels {
    public class MainPageViewModel : ViewModelBase {
        private readonly IFavoriteStorage favoriteStorage;

        public MainPageViewModel(IFavoriteStorage favoriteStorage) {
            this.favoriteStorage = favoriteStorage;
        }

        private RelayCommand _initializeCommand;

        public RelayCommand InitializeCommand =>
            _initializeCommand ?? (_initializeCommand =
                new RelayCommand(async () =>
                    await favoriteStorage.InitializeAsync()));

        public ObservableRangeCollection<Favorite> Favorites { get; } =
            new ObservableRangeCollection<Favorite>();

        private RelayCommand _getFavoritesCommand;

        public RelayCommand GetFavoritesCommand =>
            _getFavoritesCommand ?? (_getFavoritesCommand = new RelayCommand(
                async () => {
                    Favorites.Clear();
                    Favorites.AddRange(
                        await favoriteStorage.GetFavoritesAsync());
                }));

        private RelayCommand _saveFavoriteCommand;

        public RelayCommand SaveFavoriteCommand =>
            _saveFavoriteCommand ?? (_saveFavoriteCommand = new RelayCommand(
                async () => {
                    Random random = new Random();
                    var favorite = new Favorite {
                        IsFavorite = random.NextDouble() > 0.5
                    };
                    await favoriteStorage.SaveFavoriteAsync(favorite);
                }));
    }
}